import Vue from 'vue'
import VueRouter from 'vue-router'
import Welcome from './components/Welcome.vue'
import Manage from './components/Manage/Manage.vue'
import DefaultManage from './components/Manage/DefaultManage.vue'
import MangeUserClass from './components/Manage/User/MangeUserClass.vue'
import ManageUserStudent from './components/Manage/User/ManageUserStudent.vue'
import MangeDefaultUser from './components/Manage/User/MangeDefaultUser.vue'
import ManageDefaultQuestion from './components/Manage/Question/ManageDefaultQuestion.vue'
import ManageQuestionAdd from './components/Manage/Question/ManageQuestionAdd.vue'
// 已删除ManageQuestionEdit引用
import MangeUserTeacher from '@/components/Manage/User/MangeUserTeacher.vue'
import TeachTestDefault from '@/components/Manage/Teach/TeachTestDefault.vue'
import TeachTestPublish from '@/components/Manage/Teach/TeachTestPublish.vue'
import MyAnswers from '@/components/Manage/Teach/MyAnswers.vue'
import TestDetail from '@/components/Manage/Teach/TestDetail.vue'
import TestResults from '@/components/Manage/Teach/TestResults.vue'
import ManageUserRoles from '@/components/Manage/User/ManageUserRoles.vue'
import RoleManagement from '@/components/Manage/User/RoleManagement.vue'
import MyClasses from '@/components/Manage/Class/MyClasses.vue'
import ClassStudents from '@/components/Manage/Class/ClassStudents.vue'
import StudentsManagement from '@/components/Manage/Class/StudentsManagement.vue'
import VideoList from '@/components/Manage/Video/VideoList.vue'
import VideoWatch from '@/components/Manage/Video/VideoWatch.vue'
import axios from 'axios'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import './assets/css/global.css'
import SessionManager from './utils/sessionManager.js'
import PublishDetail from '@/components/Manage/Teach/PublishDetail.vue'

Vue.use(VueRouter)

const routes = [
  // 在这里自定义了一个对象的参数meta: {authRequired: true}来标记哪些路由是需要登录验证的，
  // 导航被触发的时候只要判断是否目标路由中是否有meta这个对象，且meta包含authRequired属性，其值为true。
  // 这里访问带有meta对象的路由是被拦截的。
  { path: '/', component: Welcome },
  {
    path: '/manage/:id',
    component: Manage,
    meta: {
      authRequired: true
    },
    children: [
      {
        path: '',
        redirect: to => {
          // 动态获取当前路由参数中的id
          const { id } = to.params;
          return `/manage/${id}/video/list`;
        },
        meta: {
          authRequired: true
        }
      },
      {
        path: 'home',
        component: DefaultManage,
        name: 'DefaultManage',
        meta: {
          authRequired: true
        }
      },
      {
        // 用户管理
        path: 'user', // 添加 /user 路径
        component: MangeDefaultUser,
        name: 'MangeDefaultUser',
        meta: {
          authRequired: true
        },
        children: [
          {
            path: 'teacher', // /manage/:id/user/teacher
            component: MangeUserTeacher,
            name: 'MangeUserTeacher',
            meta: {
              authRequired: true
            }
          },
          {
            path: 'class', // /manage/:id/user/class
            component: MangeUserClass,
            name: 'MangeUserClass',
            meta: {
              authRequired: true
            }
          },
          {
            path: 'student', // /manage/:id/user/student
            component: ManageUserStudent,
            name: 'ManageUserStudent',
            meta: {
              authRequired: true
            }
          },
          {
            path: 'roles', // /manage/:id/user/roles
            component: ManageUserRoles,
            name: 'ManageUserRoles',
            meta: {
              authRequired: true,
              roles: ["0"] // 只有管理员可访问
            }
          },
          {
            path: 'system-roles', // /manage/:id/user/system-roles
            name: 'RoleManagement',
            component: RoleManagement,
            meta: {
              authRequired: true,
              roles: ["0"] // 只有管理员可访问
            }
          }
        ]
      },
      {
        // 题库管理
        path: 'question',
        component: ManageDefaultQuestion,
        name: 'ManageDefaultQuestion',
        meta: {
          authRequired: true
        },
        children: [
          {
            path: 'add',
            component: ManageQuestionAdd,
            name: 'ManageQuestionAdd',
            meta: {
              authRequired: true
            }
          }
          // {
          //   path: 'edit',
          //   component: ManageQuestionEdit,
          //   name: 'ManageQuestionEdit',
          //   meta: {
          //     authRequired: true
          //   }
          // }
        ]
      },
      {
        // 试题管理
        path: 'teach',
        component: TeachTestDefault,
        name: 'TeachTestDefault',
        meta: {
          authRequired: true
        },
        children: [
          {
            path: 'myPublish',
            component: () => import('@/components/Manage/Teach/MyPublish.vue'),
            name: 'MyPublish',
            meta: {
              authRequired: true,
              roles: ["0", "1"] // 0:管理员, 1:教师
            }
          },
          {
            path: 'testPublish',
            component: TeachTestPublish,
            name: 'TeachTestPublish',
            meta: {
              authRequired: true,
              roles: ["0", "1"] // 0:管理员, 1:教师
            }
          },
          {
            path: 'myAnswers',
            component: MyAnswers,
            name: 'MyAnswers',
            meta: {
              authRequired: true
            }
          },
          {
            path: 'testDetail',
            component: TestDetail,
            name: 'TestDetail',
            meta: {
              authRequired: true
            }
          },
          {
            path: 'publishDetail',
            component: PublishDetail,
            name: 'PublishDetail',
            meta: {
              authRequired: true
            }
          },
          {
            path: 'testResults',
            component: TestResults,
            name: 'TestResults',
            meta: {
              authRequired: true
            }
          }
        ]
      },
      {
        // 视频教学
        path: 'video/list',
        component: VideoList,
        name: 'VideoList',
        meta: {
          authRequired: true
        }
      },
      {
        path: 'video/watch',
        component: VideoWatch,
        name: 'VideoWatch',
        meta: {
          authRequired: true
        }
      },
      {
        // 班级管理
        path: 'class', 
        component: MyClasses,
        name: 'MyClasses',
        meta: {
          authRequired: true
        }
      },
      {
        // 班级学生管理
        path: 'class/:classId/students', 
        component: ClassStudents,
        name: 'ClassStudents',
        meta: {
          authRequired: true
        }
      },
      {
        // 班级申请审核
        path: 'class/applications', 
        component: () => import('@/components/Manage/Class/ClassApplications.vue'),
        name: 'ClassApplications',
        meta: {
          authRequired: true,
          roles: ["0", "1"] // 0:管理员, 1:教师
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 解决Vue-Router在3.0版本以上重复点击路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') throw err
  })
}

// 路由拦截
router.beforeEach((to, from, next) => {
  if (to.matched.some(res => res.meta.authRequired)) { // 验证是否需要登陆
    // 使用SessionManager检查登录状态
    if (SessionManager.isLoggedIn()) { // 查询本地存储信息是否已经登陆
      // 检查是否有角色限制
      const hasRoleRestriction = to.matched.some(record => record.meta.roles)
      
      if (hasRoleRestriction) {
        // 找到第一个有角色限制的路由记录
        const routeWithRoles = to.matched.find(record => record.meta.roles)
        if (routeWithRoles) {
          const role = SessionManager.getUserRole()
          console.log('Current role:', role, 'type:', typeof role)
          console.log('Required roles:', routeWithRoles.meta.roles)
          console.log('Role check result:', routeWithRoles.meta.roles.includes(role))
          
          if (routeWithRoles.meta.roles.includes(role)) {
            next()
          } else {
            alert('没有权限访问')
            next({
              path: '/' // 没有权限则跳转至登录主页
            })
          }
        } else {
          next()
        }
      } else {
        next()
      }
    } else {
      alert('请先登录')
      next({
        path: '/' // 未登录则跳转至登录主页
      })
    }
  } else {
    next()
  }
})
export default router
